package com.haoyun.mirage.user.service.impl;

import com.baomidou.dynamic.datasource.DS;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.haoyun.common.cache.anno.CacheDel;
import com.haoyun.common.cache.anno.Cached;
import com.haoyun.common.constant.SecurityConstants;
import com.haoyun.common.core.BaseException;
import com.haoyun.common.utils.Query;
import com.haoyun.mirage.user.common.enums.DeptTypeEnum;
import com.haoyun.mirage.user.mapper.SysDeptMapper;
import com.haoyun.mirage.user.mapper.SysUserMapper;
import com.haoyun.mirage.user.mapper.SysUserRoleMapper;
import com.haoyun.mirage.user.model.dto.UserDTO;
import com.haoyun.mirage.user.model.entity.SysDept;
import com.haoyun.mirage.user.model.entity.SysUser;
import com.haoyun.mirage.user.model.entity.SysUserRole;
import com.haoyun.mirage.user.service.ISysUserService;
import com.xiaoleilu.hutool.bean.BeanUtil;
import com.xiaoleilu.hutool.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author twg
 * @since 2018-05-30
 */
@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysDeptMapper deptMapper;
    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Override
    @Transactional
    public Boolean insertUser(UserDTO userDTO) throws BaseException {
        Assert.notBlank(userDTO.getUserName(), "用户名不能为空");
        Assert.notNull(userDTO.getDeptId(), "部门ID不能为空");
        Assert.notEmpty(userDTO.getRoleIds(), "角色ID不能为空");
        if (isExist(userDTO.getUserName())) {
            throw new BaseException("用户[" + userDTO.getUserName() + "]已存在！");
        }
        handlerCompId(userDTO);
        SysUser sysUser = new SysUser();
        BeanUtil.copyProperties(userDTO, sysUser);
        Boolean result = this.insert(sysUser);
        //保存用户角色关系
        String[] roleIds = userDTO.getRoleIds();
        insertUserRole(sysUser.getId(), roleIds);
        return result;
    }


    @Override
    @Transactional
    public Boolean updateUser(UserDTO userDTO) throws BaseException {
        Assert.notNull(userDTO.getId(), "用户ID不能为空！");
        Assert.notNull(userDTO.getUserName(), "用户名不能为空！");
        Assert.notNull(userDTO.getDeptId(), "部门ID不能为空");
        Assert.notEmpty(userDTO.getRoleIds(), "角色ID不能为空");
        handlerCompId(userDTO);
        SysUserRole userRole = new SysUserRole();
        userRole.setUserId(userDTO.getId());
        userRoleMapper.delete(new EntityWrapper<SysUserRole>(userRole));
        //保存用户角色关系
        String[] roleIds = userDTO.getRoleIds();
        insertUserRole(userDTO.getId(), roleIds);
        SysUser sysUser = new SysUser();
        BeanUtil.copyProperties(userDTO, sysUser);
        return this.updateById(sysUser);
    }


    @DS
    @Override
    public Boolean isExist(String username) {
        Assert.notBlank(username, "用户名不能为空！");
        SysUser user = new SysUser();
        user.setUserName(username);
        SysUser sysUser = userMapper.selectOne(user);
        if (sysUser == null) {
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }


    @DS
    @Override
    public UserDTO getUserByName(String username) {
        Assert.notBlank(username, "用户名不能为空！");
        SysUser user = new SysUser();
        user.setUserName(username);
        user = userMapper.selectOne(user);
        UserDTO userDTO = new UserDTO();
        BeanUtil.copyProperties(user, userDTO);
        return userDTO;
    }

    @DS
    @Override
    public UserDTO getUserWithRoleByName(String username) {
        Assert.notBlank(username, "用户名不能为空");
        return userMapper.getUserWithRoleByName(username);
    }

    @Override
    public UserDTO getUserWithRoleDeptById(Long userId) {
        Assert.notNull(userId, "用户ID不能为空！");
        return userMapper.getUserWithRoleDeptById(userId);
    }

    public SysUser testGetSysUser(String username) {
        System.out.println(" ==== SysUserServiceImpl.testGetSysUser ===== ");
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        return userMapper.selectOne(sysUser);
    }

    @Override
    @Transactional
    public Boolean deleteUserByIdAndName(Long userId, String username) {
        Assert.notBlank(username, "用户名不能为空");
        Assert.notNull(userId, "用户id不能为空");
        return this.deleteUserById(userId);
    }

    @Override
    @Transactional
    public Boolean deleteUserById(Long userId) {
        SysUserRole userRole = new SysUserRole();
        userRole.setUserId(userId);
        userRoleMapper.delete(new EntityWrapper<SysUserRole>(userRole));
        SysUser user = new SysUser();
        user.setId(userId);
        return this.delete(new EntityWrapper<SysUser>(user));
    }

    @Override
    public List<UserDTO> findUserByCompIdUserLevel(Long compId, Integer userLevel) {
        Assert.notNull(compId, "公司ID不能为空！");
        Assert.notNull(userLevel, "用户级别不能为空！");
        return userMapper.findUserByCompIdUserLevel(compId, userLevel);
    }

    @Override
    public Page<UserDTO> findUserByPage(Query query) {
        return query.setRecords(userMapper.findUserByPage(query, query.getCondition()));
    }


    /**
     * 处理公司ID
     *
     * @param userDTO
     */
    private void handlerCompId(UserDTO userDTO) {
        SysDept dept = deptMapper.selectById(userDTO.getDeptId());
        if (dept == null) {
            log.warn("通过部门ID：{}，获取部门信息不存在。", userDTO.getDeptId());
            throw new BaseException("部门不存在！");
        }
        if (DeptTypeEnum.COMP_TYPE.getType().equals(dept.getDeptType())) {
            userDTO.setCompId(dept.getId());
        }
    }

    /**
     * 添加用户、角色关系
     *
     * @param userId
     * @param roleIds
     */
    private void insertUserRole(Long userId, String[] roleIds) {
        SysUserRole sysUserRole = null;
        for (String roleId : roleIds) {
            sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(Long.parseLong(roleId));
            sysUserRole.setUserId(userId);
            userRoleMapper.insert(sysUserRole);
        }
    }
}
